package main

import (
	"fmt"
	"net/http"
	"github.com/gorilla/mux"
	"strconv"
	"encoding/json"
	"log"
	"io/ioutil"
)

const (
	APP_NAME = "Blue/Green"
)

type Artist struct {
	Name string `json:"name"`
}

type Route struct {
	Name        string
	Method      string
	Pattern     string
	HandlerFunc http.HandlerFunc
}

type Routes []Route

var routes = Routes{
	Route{
		"GetArtist",
		"GET",
		"/artist/rank",
		GetRankingFirst,
	},
}

func NewRouter() *mux.Router {
	router := mux.NewRouter().StrictSlash(true)

	for _, route := range routes {
		router.Methods(route.Method).
			Path(route.Pattern).
			Name(route.Name).
			Handler(route.HandlerFunc)
	}
	return router
}

func GetRankingFirst(w http.ResponseWriter, r *http.Request) {
	log.Print("正在获取榜单")
	rank, err := ioutil.ReadFile("rank")
	if err != nil {
		panic(err)
	}
	artist := Artist{Name: string(rank)}
	//artist := Route{Name:"汪峰"}

	data, _ := json.Marshal(artist)
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.Header().Set("Content-Length", strconv.Itoa(len(data)))
	w.WriteHeader(http.StatusOK)
	w.Write(data)
}

func StartWebServer(port string) {
	r := NewRouter()
	http.Handle("/", r)

	log.Printf("正在监听端口 %s", port)
	err := http.ListenAndServe(fmt.Sprintf(":%v", port), nil)
	if err != nil {
		log.Println("无法监听端口,请检查是否被占用 " + port)
		log.Println("错误信息: " + err.Error())
	}
}

func main() {
	fmt.Printf("Starting %v\n ", APP_NAME)
	StartWebServer("6000")
}
